package com.xinqi.modules.prepare.discuss.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.current.Currents;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.prepare.common.dto.data.PrepareDiscussData;
import com.xinqi.modules.prepare.common.service.PrepareAuthService;
import com.xinqi.modules.prepare.discuss.convert.PrepareDiscussConvert;
import com.xinqi.modules.prepare.discuss.domain.PrepareDiscussEntity;
import com.xinqi.modules.prepare.discuss.dto.req.PrepareDiscussCreateDTO;
import com.xinqi.modules.prepare.discuss.dto.req.PrepareDiscussDeleteDTO;
import com.xinqi.modules.prepare.discuss.dto.req.PrepareDiscussQueryDTO;
import com.xinqi.modules.prepare.discuss.dto.req.PrepareDiscussUpdateDTO;
import com.xinqi.modules.prepare.discuss.dto.rsp.PrepareDiscussResultDTO;
import com.xinqi.modules.prepare.discuss.manager.PrepareDiscussManager;
import com.xinqi.modules.prepare.discuss.service.PrepareDiscussService;
import com.xinqi.modules.prepare.folder.manager.PrepareFileFolderManager;
import com.xinqi.modules.prepare.prepare.enums.PrepareMemberPermissionEnum;
import com.xinqi.modules.prepare.prepare.enums.PrepareOperateTypeEnum;
import com.xinqi.modules.prepare.prepare.enums.PrepareSubOperateTypeEnum;
import com.xinqi.modules.prepare.prepare.manager.PrepareOperateLogManager;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 备课区讨论服务层实现
 *
 * @author: system
 * @date: 2023/03/19
 */
@Validated
@Service("prepareDiscussService")
@RequiredArgsConstructor
public class PrepareDiscussServiceImpl implements PrepareDiscussService {
    private final PrepareDiscussConvert prepareDiscussConvert;
    private final PrepareDiscussManager prepareDiscussManager;
    private final PrepareAuthService prepareAuthService;
    private final PrepareFileFolderManager prepareFileFolderManager;
    private final PrepareOperateLogManager prepareOperateLogManager;


    /**
     * 分页查询 备课区讨论数据
     */
    @Override
    @DS("slaver")
    public PageInfo<PrepareDiscussResultDTO> page(Param pageable, PrepareDiscussQueryDTO query) {
        IPage<PrepareDiscussEntity> page = prepareDiscussManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, prepareDiscussConvert::convert);
    }

    /**
     * 查询 备课区讨论数据
     */
    @Override
    public List<PrepareDiscussResultDTO> find(PrepareDiscussQueryDTO query) {
        return prepareDiscussManager.list(wrapper(query)).stream()
                .map(prepareDiscussConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<PrepareDiscussEntity> wrapper(PrepareDiscussQueryDTO query) {
        LambdaQueryWrapper<PrepareDiscussEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(PrepareDiscussEntity::getId, v));
        Queries.accept(query.getPrepareId(), v -> wrapper.eq(PrepareDiscussEntity::getPrepareId, v));
        return wrapper;
    }

    /**
     * 根据id查询 备课区讨论数据
     */
    @Override
    public PrepareDiscussResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(prepareDiscussManager.findById(id)).map(prepareDiscussConvert::convert).orElse(null);
    }

    @Override
    public PrepareDiscussData find(Long id) {
        return prepareDiscussConvert.convert(findById(id));
    }

    /**
     * 新增 备课区讨论数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid PrepareDiscussCreateDTO dto) {
        prepareAuthService.check(dto.getPrepareId(), PrepareMemberPermissionEnum.新建);
        PrepareDiscussEntity entity = prepareDiscussConvert.create(dto);
        entity.setUserId(Currents.userId());
        prepareDiscussManager.save(entity);
        // 创建备课区文件
        prepareFileFolderManager.insertFile(entity, entity.getPrepareId(), dto.getFolderId(), dto.getIsAutoGenerateName());
        prepareOperateLogManager.addFileOperateLog(entity, PrepareOperateTypeEnum.FILE_EDIT, PrepareSubOperateTypeEnum.ADD);
        return entity.getId();
    }

    @Override
    public Long insert(PrepareDiscussData data) {
        PrepareDiscussCreateDTO dto = prepareDiscussConvert.create(data);
        return insert(dto);
    }

    /**
     * 根据id修改 备课区讨论数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid PrepareDiscussUpdateDTO dto) {
        PrepareDiscussEntity old = Optional.ofNullable(prepareDiscussManager.getById(dto.getId()))
                .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        prepareAuthService.check(old.getPrepareId(), PrepareMemberPermissionEnum.编辑);
        PrepareDiscussEntity entity = prepareDiscussConvert.update(dto);
        boolean b = prepareDiscussManager.updateById(entity);
        if (b) {
            // 更新备课区文件
            PrepareDiscussEntity newEntity = prepareDiscussManager.getById(dto.getId());
            prepareFileFolderManager.updateFile(newEntity, newEntity.getPrepareId());
            prepareOperateLogManager.addFileOperateLog(newEntity, PrepareOperateTypeEnum.FILE_EDIT, PrepareSubOperateTypeEnum.EDIT);
        }
        return b;
    }

    /**
     * 根据id删除 备课区讨论数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        PrepareDiscussEntity entity = Optional.ofNullable(prepareDiscussManager.getById(id))
                .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        prepareAuthService.check(entity.getPrepareId(), PrepareMemberPermissionEnum.删除);
        boolean b = prepareDiscussManager.deleteById(entity);
        if (b) {
            // 删除备课区文件
            prepareFileFolderManager.deleteFile(entity, entity.getPrepareId());
        }
        return b;
    }

    /**
     * 根据id删除 备课区讨论数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(PrepareDiscussDeleteDTO dto) {
        return deleteById(dto.getId());
    }

}
